<template>
  <div >
    <mt-field
      label="账号"
      placeholder="请输入账号"
      v-model="loginForm.name"
    />

    <mt-field
      label="密码"
      placeholder="请输入密码"
      type="password"
      v-model="loginForm.password"
    ></mt-field>

    <mt-button @click="onClickLogin" size="large">登录</mt-button>
    <div class="link-area">
      <a @click="register">还没有账号？前往注册</a>
    </div>
  </div>
</template>

<script>
//import { mapGetters, mapState } from "vuex";
import { mapActions } from 'vuex'
import { mapState } from "vuex"; // mapGetters
export default {
  data() {
    return {
      loginForm: {
        name: "",
        password: "",
      },
      userToken: "",
    };
  },
  mounted(){
    this.loginForm.name = this.user.name;//初始赋值
  },
  computed: {
    ...mapState("user",["user"]),     
  },
  methods: {
    ...mapActions("user",["login" ]),// `mapActions` 支持载荷将 `this.login(user)` 映射为 `this.$store.dispatch('login', user)`
   
    async onClickLogin() {
      if (this.loginForm.name === "" || this.loginForm.password === "") {
        this.$toast("账号或密码不能为空");
        return ;
      }      
      try {
        let user = this.loginForm;
        let result = await this.login(user); // `mapActions` 支持载荷将
        if(result.code == 1) {
          this.$toast("登录成功！")   
          this.$router.replace({ name: "user" });
        }else{
          throw result.msg;
        }  
      } catch (error) {
        this.$messagebox("登录失败",error);  
      }
    },
    register() {
      this.$router.push({ name: "register" });
    },
  },
};
</script>

<style lang="scss" scoped>
.link-area {
  display: block;
  margin-top: 25px;
  text-align: center;
}
</style>
